package com.keeley.model;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.TableMapping;
import com.keeley.interceptor.Seach;

public class SeachModel<T extends Model<T>> extends Model<T> {

	private static final long serialVersionUID = 7221585097803321618L;
	
	public Page<T> paginate(int pageNumber,int rows){
		return this.paginate(pageNumber,rows,null);
	}
	public Page<T> paginate(int pageNumber,int rows,Seach seach){
		String select="select * ";
		String sqlExceptSelect = " from "+getTableName()+" where 1=1 ";
		return this.paginateBySelect(select, sqlExceptSelect, pageNumber, rows, seach);
	}
	/**
	 * 关联 shop_name的查询
	 * @param pageNumber
	 * @param rows
	 * @param seach
	 * @return
	 */
	public Page<T> paginateHasShop(int pageNumber,int rows,Seach seach){
		String tableName = getTableName();
		String select="select a.*,s.name as shop_name";
		String sqlExceptSelect = " from "+tableName+" a left join shop s on a.shop_id = s.id where 1=1 ";
		return paginateBySelect(select, sqlExceptSelect, pageNumber, rows, seach);
	}
	
	public Page<T> paginateBySelect(String select,String sqlExceptSelect,int pageNumber,int rows,Seach seach){
		//String select="select * ";
		//String sqlExceptSelect = " from product where 1=1 left join ";
		if(seach!=null){
			sqlExceptSelect+= seach.getSqlWhere();
			sqlExceptSelect+= seach.getOrderBy();
			return super.paginate(pageNumber,rows, select, sqlExceptSelect,seach.getSqlParam().toArray());
		}
		return super.paginate(pageNumber, rows, select, sqlExceptSelect);
	}
	
	private String getTableName(){
		return TableMapping.me().getTable(getClass()).getName();
	}
	
}
